package org.l.qiao.builder;

import org.l.qiao.Cluster;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Update extends Cluster {

    public static final String SET = "$set"; //设置部分键值
    public static final String UNSET = "$unset"; //删除键
    /**
     * $pullAll,从列表中删除匹配值
     */
    public static final String PULL_ALL = "$pullAll";
    public static final String PUSH = "$push";
    public static final String EACH = "$each";
    public static final String SLICE = "$slice";
    public static final String SORT = "$sort";
    public static final String POSITION = "$position";

    public static final String INC = "$inc";

    public Update() {
        super();
    }

    public Update(Map<String, Object> map) {
        super(map);
    }

    public Update(String name, Object value) {
        super(name, value);
    }

    /**
     * 设置修改键，自动添加为$set的子文档
     *
     * @param key
     * @param value
     */
    public void set(String key, Object value) {
        Map set = new HashMap<>();
        set.put(key, value);
        put(this.SET, set);
    }

    public void set(Map update) {
        put(this.SET, update);
    }

    /**
     * 设置删除键，自动添加为$unset的子文档
     *
     * @param key
     */
    public void unset(String key) {
        Map unset = new HashMap<>();
        unset.put(key, false);
        elput(this.UNSET, unset);
    }

    public void unset(Map update) {
        put(this.UNSET, update);
    }

    /**
     * 从列表中删除匹配值
     */
    public Object pullAll(String key, Object value) {
        return this.put(PULL_ALL, new Cluster(key, value));
    }

    public Object push(String key, List value, int slice, Object sort, int position) {
        Cluster cluster = new Cluster();
        cluster.put(EACH, value);

        if (sort != null) {
            cluster.put(SORT, sort);
        }

        cluster.put(SLICE, slice);
        cluster.put(POSITION, position);
        Map push = getMap(PUSH, new HashMap());
        push.put(key, cluster);
        return put(PUSH, push);
    }

    public Object push(String key, List value, Object sort, int position) {
        Cluster cluster = new Cluster();
        cluster.put(EACH, value);

        if (sort != null) {
            cluster.put(SORT, sort);
        }

        cluster.put(POSITION, position);
        Map push = getMap(PUSH, new HashMap());
        push.put(key, cluster);
        return put(PUSH, push);
    }

    /**
     * 加法计算
     *
     * @param key
     * @param value
     */
    public void inc(String key, long value) {
        elput(INC + '.' + key, value);
    }
}
